/*
 * ProbCalculator.cpp
 *
 *  Created on: Feb 7, 2012
 *      Author: sd
 */

#include "ProbCalculator.h"
#include <iostream>

using std::cerr;

ProbCalculator::ProbCalculator() {
	atLeastOneFullLine = false;
	probToBuildThisLine = 1;
	probOfNotBuildingAnyLine = 1;
	k=0;
	queue = new float[numToWin];
}

ProbCalculator::ProbCalculator(int numToWin1) {
	//cerr << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!11----------------\n";
	atLeastOneFullLine = false;
	probToBuildThisLine = 1;
	probOfNotBuildingAnyLine = 1;
	k=0;
	queue = new float[numToWin1];
	for (int k1=0;k1<numToWin1; k1++) queue[k1]=0;
	numToWin = numToWin1;
}

void ProbCalculator::push(int y_h) {
	float p = (y_h<0  ? 1.0   :
			   y_h==0 ? 0.4 :
		       y_h==1 ? 0.9 :
			   0.5);
	//cerr << "p=" <<p<<"\n";
	if (!atLeastOneFullLine) {
		//cerr << "k=" <<k<<", p="<<p<<", size="<<sizeof(queue)/sizeof(float)<<"\n";
		//cerr <<"try queue[i]\n";
		//cerr << queue[k];
		queue[k] = p;
		//cerr <<"done\n";
		probToBuildThisLine =p * probToBuildThisLine;
		//cerr <<i;
		k++;
		if (k == numToWin) {
			k=0;
			atLeastOneFullLine=true;
			//cerr << "k="<<k<<", pl=" << probToBuildThisLine<< "\n";
			probOfNotBuildingAnyLine = probOfNotBuildingAnyLine*(1-probToBuildThisLine);
		}
	} else {
		probToBuildThisLine *= p/queue[k];
		queue[k] = p;
		probOfNotBuildingAnyLine = probOfNotBuildingAnyLine*(1-probToBuildThisLine);
		k++;
		if (k == numToWin) k=0;
	}
}

float ProbCalculator::getProb() {
	return 1 - probOfNotBuildingAnyLine;
}

void ProbCalculator::reset() {
	atLeastOneFullLine = false;
	k=0;
	probToBuildThisLine = 1;
	probOfNotBuildingAnyLine = 1;
}

void ProbCalculator::changeDirection() {
	atLeastOneFullLine = false;
	k=0;
	probToBuildThisLine = 1;
	//cerr << "--\n";
}
